<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2018-05-22
 * Time: 10:51
 */

namespace app\api\service;

use app\lib\enum\OrderStatusEnum;
use app\lib\exception\OrderException;
use app\lib\exception\RefundException;
use app\lib\exception\TokenException;
use think\Exception;
use app\api\model\Refund as RefundModel;
use app\api\model\Order as OrderModel;
use think\Loader;
use think\Log;

Loader::import('WxPay.WxPay', EXTEND_PATH, '.Api.php');

class Refund
{
    private $orderNo;
    private $orderID;
    private $refundNo;
    private $refundID;

    function __construct($refundID){
        if (!$refundID){
            throw new Exception('退款单号不允许为NULL');
        }
        $this->refundID = $refundID;
    }

    public function refund(){
        $this->checkRefundValid();
        $refund = RefundModel::where('id', '=', $this->refundID)->find();
        $order = $refund->order()->where('id', '=', $refund->oid)->find();
        if($order->status != OrderStatusEnum::AUDIT_PASS){
            throw new RefundException([
                'msg' => '退款申请不是审核通过状态，出现异常',
                'errorCode' => 80004,
                'code' => 400
            ]);
        }
        return $this->makeWxRefund($order->total_price, $refund->money);
    }

    // 构建微信退款订单信息
    private function makeWxRefund($order_money, $refund_money){
        // $openid = Token::getCurrentTokenVar('openid');
        // if (!$openid){
        //    throw new TokenException();
        // }
        $wxRefundData = new \WxPayRefund();
        $wxRefundData->SetOut_trade_no($this->orderNo);
        $wxRefundData->SetOut_refund_no($this->refundNo);
        $wxRefundData->SetTotal_fee($order_money * 100);
        $wxRefundData->SetRefund_fee($refund_money * 100);
        $wxRefundData->SetOp_user_id(\WxPayConfig::MCHID);
		
        $wxRefund = \WxPayApi::refund($wxRefundData);
		
        // 失败时不会返回result_code
        if($wxRefund['return_code'] != 'SUCCESS' || $wxRefund['result_code'] !='SUCCESS'){
            Log::record($wxRefund,'error');
            Log::record('退款失败','error');
            // throw new Exception('退款失败');
        }elseif($wxRefund['return_code'] == 'SUCCESS' || $wxRefund['result_code'] =='SUCCESS'){
            $this->updateOrderStatus();
        }
        return  $wxRefund;
    }

    private function updateOrderStatus(){
        $status = OrderStatusEnum::HAVE_A_REFUND;
        OrderModel::where('id', '=', $this->orderID)->update(['status' => $status]);
    }

    private function checkRefundValid(){
        $refund = RefundModel::where('id', '=', $this->refundID)->find();
        $order = $refund->order()->where('id', '=', $refund->oid)->find();
        if (!$refund){
            throw new RefundException();
        }
        if(!$order){
            throw new OrderException();
        }
        if($order->user_id != $refund->uid){
            throw new TokenException([
                'msg' => '订单与或申请退款单用户不匹配',
                'errorCode' => 10003
            ]);
        }
        if($order->status != OrderStatusEnum::AUDIT_PASS){
            throw new RefundException([
                'msg' => '退款申请未审核或审核拒绝',
                'errorCode' => 80009,
                'code' => 400
            ]);
        }
        $this->orderNo = $order->order_no;
        $this->orderID = $refund->oid;
        $this->refundNo = $refund->refund_no;
		
        return true;
    }

}